#nullable disable

using System.Collections;

namespace System;
/// <summary>
/// EnvironmentExtensions
/// </summary>
public class EnvironmentExtensions
{
    /// <summary>
    ///
    /// </summary>
    private static readonly IEnumerable<KeyValuePair<string, string>> environmentVariables = Environment.GetEnvironmentVariables()
                                                      .Cast<DictionaryEntry>()
                                                      .Select(p => new KeyValuePair<string, string>(p.Key.ToString(), p.Value.ToString()));
    /// <summary>
    ///
    /// </summary>
    /// <param name="envKey"></param>
    /// <param name="value"></param>
    /// <param name="defalutValue"></param>
    /// <returns></returns>
    public static bool TryGetEnv(string envKey, out string value, string defalutValue = default)
    {
        if (!environmentVariables.TryGetValue(p => p.Key == envKey, out var valueEntry, new KeyValuePair<string, string>(envKey, defalutValue)))
        {
            value = defalutValue;
            return false;
        }
        value = valueEntry.Value;
        return true;
    }

    /// <summary>
    ///
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="envKey"></param>
    /// <param name="value"></param>
    /// <param name="defalutValue"></param>
    /// <returns></returns>
    public static bool TryGetEnv<T>(string envKey, out T value, T defalutValue = default)
    {
        if (!TryGetEnv(envKey, out string stringValue))
        {
            value = defalutValue;
            return false;
        }
        try
        {
            value = (T)Convert.ChangeType(stringValue, typeof(T));
            return true;
        }
        catch (Exception)
        {
            value = defalutValue;
            return false;
        }
    }

}